package entity

import (
	"github.com/astaxie/beego/orm"
	"github.com/gomodule/redigo/redis"
	"nspel/nspel"
	"strconv"
)

type Province struct {
	Id        int64  `orm:"pk;auto;column(id)"`
	CountryId int64  `orm:"column(country_id)"`
	Name      string `orm:"column(name)"`
}

func init() {
	orm.RegisterModel(new(Province))
}

func (*Province) TableName() string {
	return "province"
}

func (p *Province) SelectAllByName(name string) error {
	p.Name = name
	key := "province"
	hashKey := "name[\"" + name + "\"]"
	err := nspel.RedisHgetJson(key, hashKey, p)
	if err == nil {
		return nil
	}
	if err != redis.ErrNil {
		nspel.Error(err)
	}
	err = nspel.GetOrmEngine().Read(p, "name")
	if err != nil {
		return err
	}
	nspel.RedisHsetJson(key, hashKey, p)
	return nil
}

func (p *Province) SelectAllByCountryIdName(countryId int64, name string) error {
	p.CountryId = countryId
	p.Name = name
	key := "province"
	hashKey := "countryId[" + strconv.FormatInt(countryId, 10) + "].name[\"" + name + "\"]"
	err := nspel.RedisHgetJson(key, hashKey, p)
	if err == nil {
		return nil
	}
	if err != redis.ErrNil {
		nspel.Error(err)
	}
	err = nspel.GetOrmEngine().Read(p, "country_id", "name")
	if err != nil {
		return err
	}
	nspel.RedisHsetJson(key, hashKey, p)
	return nil
}

func (p *Province) SelectAllByCountryId(countryId int64) ([]Province, error) {
	p.CountryId = countryId
	key := "province"
	hashKey := "countryId[" + strconv.FormatInt(countryId, 10) + "]"
	var provinces []Province
	err := nspel.RedisHgetJson(key, hashKey, &provinces)
	if err == nil {
		return provinces, nil
	}
	if err != redis.ErrNil {
		nspel.Error(err)
	}
	_, err = nspel.GetOrmEngine().QueryTable(p.TableName()).Filter("country_id", countryId).All(&provinces)
	if err != nil {
		return nil, err
	}
	if len(provinces) == 0 {
		return provinces, orm.ErrNoRows
	}
	nspel.RedisHsetJson(key, hashKey, provinces)
	return provinces, nil
}

func (p *Province) SelectAll() ([]Province, error) {
	key := "province"
	hashKey := "all"
	var provinces []Province
	err := nspel.RedisHgetJson(key, hashKey, &provinces)
	if err == nil {
		return provinces, nil
	}
	if err != redis.ErrNil {
		nspel.Error(err)
	}
	_, err = nspel.GetOrmEngine().QueryTable(p.TableName()).All(&provinces)
	if err != nil {
		return nil, err
	}
	if len(provinces) == 0 {
		return provinces, orm.ErrNoRows
	}
	nspel.RedisHsetJson(key, hashKey, provinces)
	return provinces, nil
}

func (p *Province) SelectAllById(id int64) error {
	key := "province"
	hashKey := "id[" + strconv.FormatInt(id, 10) + "]"
	err := nspel.RedisHgetJson(key, hashKey, p)
	if err == nil {
		return nil
	}
	if err != redis.ErrNil {
		nspel.Error(err)
	}
	p.Id = id
	err = nspel.GetOrmEngine().Read(p)
	if err != nil {
		return err
	}
	nspel.RedisHsetJson(key, hashKey, p)
	return nil
}
